﻿using CPPEI.Coolzon.Common;
using CPPEI.Coolzon.ServiceProxy.DataServiceRef;
using CPPEI.Coolzon.UI.Converters;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Visifire.Charts;

namespace CPPEI.Coolzon.UI.DataPartLib
{
    /// <summary>
    /// Interaction logic for DataChartArea.xaml
    /// </summary>
    [System.ComponentModel.DisplayName("区域图")]
    [XPartIcon("pack://application:,,,/CPPEI.Coolzon.UI.DataPartLib;component/Images/PartIcons/区域图.png")]
    [XPart("ChartArea", "区域图")]
    public partial class DataChartArea : DataChartAxisBase
    {
        private List<ValueFlag> _dictDPValue;

        public double DataAnimationProgress
        {
            get
            {
                return (double)GetValue(DataAnimationProgressProperty);
            }
            set
            {
                SetValue(DataAnimationProgressProperty, value);
            }
        }

        public static DependencyProperty DataAnimationProgressProperty = DependencyProperty.Register("DataAnimationProgress",
            typeof(double),
            typeof(DataChartArea),
            new PropertyMetadata(default(double), OnDataAnimationProgressPropertyChangedCallback));

        private static void OnDataAnimationProgressPropertyChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            DataChartArea dObject = d as DataChartArea;
            dObject.UpdateDataAnimationProcess();
        }

        private void UpdateDataAnimationProcess()
        {
            double progress = this.DataAnimationProgress;
            int loopend = (int)(_dataSerieAllCount * progress);
            for (int i = _index; i < loopend; i++)
            {
                if (_dictDPValue[i].DataSeries.DataPoints.Count >= _dictDPValue[i].Index + 1)
                {
                    _dictDPValue[i].DataSeries.DataPoints.RemoveAt(_dictDPValue[i].Index);
                    _dictDPValue[i].DataPoint.YValue = _dictDPValue[i].EndValue;
                    _dictDPValue[i].DataSeries.DataPoints.Insert(_dictDPValue[i].Index, _dictDPValue[i].DataPoint);
                }
                else
                {
                    Common.Logger.WarningToTag("DataPartArea", "UpdateDataAnimationProcess loopend:{0} 大于DataSeries.DataPoints.Count,_dataSerieAllCount:{1},progress={2}", loopend, _dataSerieAllCount, progress);
                }
            }
            _index = loopend;
        }

        /// <summary>
        /// 数据加载动画
        /// </summary>
        private DoubleAnimation _doubleAnimation;
        private int _index;
        /// <summary>
        /// 所有串所有项的总数目
        /// </summary>
        private int _dataSerieAllCount;
        
        public DataChartArea()
        {
            AxisXStartFromZero = true;
            InitializeComponent();

            _dictDPValue = new List<ValueFlag>();
        }

        protected override void OnDataBinding(DataResult dataResult)
        {
            ClearAnimation();
            StopAnimation();
            _animationStoryboard = new Storyboard();
            _animationStoryboard.Completed += _animationStoryboard_Completed;
            _animationStoryboard.AccelerationRatio = 0.2d;
            _animationStoryboard.DecelerationRatio = 0.3d;
            _doubleAnimation = new DoubleAnimation(0, 1, new Duration(TimeSpan.FromSeconds(XDataAnimationDuration)));
            Storyboard.SetTarget(_doubleAnimation, this);
            Storyboard.SetTargetProperty(_doubleAnimation, new PropertyPath(DataChartArea.DataAnimationProgressProperty));
            _animationStoryboard.Children.Add(_doubleAnimation);

            _ctlChart.Series.Clear();

            double maxYValue = 0;
            double minYValue = 0;

            double max2ndYValue = 0;
            double min2ndYValue = 0;

            if (dataResult.DataSeries.Length > 0)
            {
                _index = 0;
                _dataSerieAllCount = 0;
                _dictDPValue.Clear();

                foreach (ServiceProxy.DataServiceRef.DataSeries dataSerie in DataResult.DataSeries)
                {
                    Visifire.Charts.DataSeries vfdataSeries = new Visifire.Charts.DataSeries();
                    if (LineThickness != null)
                    {
                        vfdataSeries.LineThickness = LineThickness;
                    }
                    vfdataSeries.RenderAs = GetRender(dataSerie.Id);
                    vfdataSeries.Name = dataSerie.Name;
                    vfdataSeries.LegendText = dataSerie.Name;
                    vfdataSeries.Bevel = DataSeriesBevel;
                    vfdataSeries.ShowInLegend = LegendEnabled;
                    vfdataSeries.LineStyle = GetLineStyle(dataSerie.Id);
                    //设置Y轴类型 Primary或者Secondary
                    if (SeriesYAxisType != null && SeriesYAxisType.ContainsKey(dataSerie.Id))
                    {
                        vfdataSeries.AxisYType = (AxisTypes)Enum.Parse(typeof(AxisTypes), SeriesYAxisType[dataSerie.Id]);
                    }

                    _dataSerieAllCount += dataSerie.DataItems.Length;

                    int itemIndex = 0;
                    foreach (ServiceProxy.DataServiceRef.DataItem dataItem in dataSerie.DataItems)
                    {
                        double dItemValue = Convertor.ToDouble(dataItem.Value);
                        if (vfdataSeries.AxisYType == AxisTypes.Secondary)
                        {
                            if (dItemValue > max2ndYValue)
                            {
                                max2ndYValue = dItemValue;
                            }
                            else if (dItemValue < min2ndYValue)
                            {
                                min2ndYValue = dItemValue;
                            }
                        }
                        else
                        {
                            if (dItemValue > maxYValue)
                            {
                                maxYValue = dItemValue;
                            }
                            else if (dItemValue < minYValue)
                            {
                                minYValue = dItemValue;
                            }
                        }

                        DataPoint datapoint = new DataPoint();
                        datapoint.Name = dataItem.Name;
                        datapoint.LegendText = dataItem.Name;
                        datapoint.YValue = AxisYMinimum;
                        datapoint.ShowInLegend = LegendEnabled;
                        FormatDataPoint(vfdataSeries, datapoint, dataItem.Name);
                        SetDataPoint(datapoint);
                        vfdataSeries.DataPoints.Add(datapoint);

                        _dictDPValue.Add(new ValueFlag(datapoint.YValue, dItemValue, vfdataSeries, datapoint, itemIndex++));
                    }
                    _ctlChart.Series.Add(vfdataSeries);
                }
            }

            _animationStoryboard.Begin(this);

            SetLegends(_ctlChart.Legends);

            ApplyChartColorPlate(_ctlChart, XColorPlate);

            AutoReviseYAxis(minYValue, maxYValue);
            AutoRevise2ndYAxis(min2ndYValue, max2ndYValue);
        }

        protected override Chart GetChart()
        {
            return _ctlChart;
        }
        protected override RenderAs GetRender(string dataSeriesId)
        {
            return RenderAs.Area;
        }
    }
}
